package controllers

import (
	"crypto/md5"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"user2/cache"
	"user2/models"
)

type User2Controller struct {
	beego.Controller
}

func Md5(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	return fmt.Sprintf("%x", has)
}

type JsonR struct {
	Code     int         `json:"code"`
	Msg      string      `json:"msg"`
	Database interface{} `json:"database"`
}

func (c *User2Controller) Create() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = JsonR{
			Code:     500,
			Msg:      "账号跟密码不能为空",
			Database: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User2
	user.Username = username
	user.Password = Md5(password)
	if user.Create() != nil {
		c.Data["json"] = JsonR{
			Code:     500,
			Msg:      "注册失败",
			Database: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = JsonR{
		Code:     200,
		Msg:      "注册成功",
		Database: nil,
	}
	c.ServeJSON()
}
func (c *User2Controller) CreateLogin() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = JsonR{
			Code:     500,
			Msg:      "账号跟密码不能为空",
			Database: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User2
	user.Username = username
	user.Password = password
	key := "list_login" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = JsonR{
			Code:     500,
			Msg:      "登录次数过多",
			Database: nil,
		}
		c.ServeJSON()
		return
	}
	if user.CreateLogin(username) != nil {
		c.Data["json"] = JsonR{
			Code:     500,
			Msg:      "登录失败",
			Database: nil,
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = JsonR{
			Code:     500,
			Msg:      "用户不存在",
			Database: nil,
		}
		c.ServeJSON()
		return
	}
	if user.Password != Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if count > 3 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*5)
		}
		c.Data["json"] = JsonR{
			Code:     500,
			Msg:      "密码不正确",
			Database: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = JsonR{
		Code:     200,
		Msg:      "登录成功",
		Database: nil,
	}
	c.ServeJSON()
}
